package com.zenithmind.common.interceptor;

import com.zenithmind.common.context.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 租户上下文拦截器
 * 从请求头中提取租户信息并设置到上下文中
 * 
 * @author ZenithMind
 * @since 2024-06-30
 */
@Slf4j
public class TenantContextInterceptor implements HandlerInterceptor {

    private static final String TENANT_ID_HEADER = "X-Tenant-Id";
    private static final String TENANT_CODE_HEADER = "X-Tenant-Code";
    private static final String USER_ID_HEADER = "X-User-Id";
    private static final String USERNAME_HEADER = "X-Username";
    private static final String USER_ROLES_HEADER = "X-User-Roles";

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, 
                           @NonNull HttpServletResponse response, 
                           @NonNull Object handler) {
        try {
            // 从请求头中提取租户信息
            String tenantId = request.getHeader(TENANT_ID_HEADER);
            String tenantCode = request.getHeader(TENANT_CODE_HEADER);
            String userId = request.getHeader(USER_ID_HEADER);
            String username = request.getHeader(USERNAME_HEADER);
            String userRoles = request.getHeader(USER_ROLES_HEADER);

            // 设置租户上下文
            if (StringUtils.hasText(tenantId)) {
                UserContext.setTenantId(tenantId);
                log.debug("设置租户ID: {}", tenantId);
            } else {
                // 如果没有租户ID，设置默认租户
                UserContext.setTenantId("default");
                log.debug("使用默认租户ID: default");
            }

            if (StringUtils.hasText(tenantCode)) {
                UserContext.setTenantCode(tenantCode);
                log.debug("设置租户编码: {}", tenantCode);
            } else {
                UserContext.setTenantCode("default");
                log.debug("使用默认租户编码: default");
            }

            // 设置用户上下文（如果存在）
            if (StringUtils.hasText(userId)) {
                UserContext.setUserId(userId);
                log.debug("设置用户ID: {}", userId);
            }

            if (StringUtils.hasText(username)) {
                UserContext.setUsername(username);
                log.debug("设置用户名: {}", username);
            }

            if (StringUtils.hasText(userRoles)) {
                UserContext.setUserRoles(userRoles);
                log.debug("设置用户角色: {}", userRoles);
            }

            return true;
        } catch (Exception e) {
            log.error("设置租户上下文时发生异常", e);
            // 即使发生异常也继续处理请求，但设置默认租户
            UserContext.setTenantId("default");
            UserContext.setTenantCode("default");
            return true;
        }
    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest request, 
                              @NonNull HttpServletResponse response, 
                              @NonNull Object handler, 
                              Exception ex) {
        // 清理ThreadLocal，防止内存泄漏
        try {
            UserContext.clear();
            log.debug("清理租户上下文完成");
        } catch (Exception e) {
            log.error("清理租户上下文时发生异常", e);
        }
    }
}
